package com.rssfeed.view;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import org.jsoup.select.Elements;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rssfeed.database.DBController;
import com.rssfeed.model.RSSFeed;
import com.rssfeed.parser.GetLinkMp3Callback;
import com.rssfeed.parser.ParseHtmlAsyncTask;
import com.rssfeed.utility.Utilities;
import com.rssfeed.utility.Utility;
import com.rssfeed.voa.R;

public class RssDetailsActitvity extends Activity implements
		OnCompletionListener, SeekBar.OnSeekBarChangeListener, GetLinkMp3Callback {

	private RSSFeed rssFeed = null;
	private TextView tvDetails;
	private TextView tvTitle;
	private String mp3Link = null;
	private String link;
	private DBController dbc;

	private Button btnPlay;
	private ImageButton btnRepeat;
	private SeekBar songProgressBar;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	private Utilities utils;
	private boolean isRepeat = false;
	private String mFeedId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rss_feed_details);

		tvDetails = (TextView) findViewById(R.id.details);
//		tvTitle = (TextView) findViewById(R.id.title);
		btnPlay = (Button) findViewById(R.id.btnPlay);
//		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
			
		// get rss
		rssFeed = (RSSFeed) getIntent()
				.getSerializableExtra("RssFeedStructure");
		mFeedId = rssFeed.getFeedId();
		String description = rssFeed.getDescription();
		String title = rssFeed.getTitle();
		link = rssFeed.getLink();
		
		if (rssFeed.getMp3Link() == null) {
			mp3Link = getMp3Link(link);
			if (mp3Link != null) {
				dbc = new DBController(this);
				dbc.updateMp3Link(mFeedId, mp3Link);
			} else {
				Toast.makeText(getApplicationContext(),
						"Can not get Mp3 Link from server", Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			mp3Link = rssFeed.getMp3Link();		
		}
		
		if(mp3Link==null){
			songCurrentDurationLabel.setVisibility(View.INVISIBLE);
			songTotalDurationLabel.setVisibility(View.INVISIBLE);
		}
		
		Log.d("mp3Link", "=" + mp3Link);
		// Mediaplayer
		mp = new MediaPlayer();
		utils = new Utilities();
	
		tvDetails.setText(description);
//		tvTitle.setText(title);

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important
		mp.setOnCompletionListener(this); // Important

		// Changing Button Image to pause image
		btnPlay.setBackgroundResource(R.drawable.down_button_running);

		// set Progress bar values
		songProgressBar.setProgress(0);
		songProgressBar.setMax(100);

		songCurrentDurationLabel.setText("0:00");
		songTotalDurationLabel.setText("0:00");

		// Updating progress bar
//		updateProgressBar();

		btnPlay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check for already playing
				if (mp.isPlaying()) {
					if (mp != null) {
						mp.pause();
						// Changing button image to play button
						btnPlay.setBackgroundResource(R.drawable.down_button_pause);
					}
				} else {
					// Resume song
					if (mp != null) {
						mp.start();
						// Changing button image to pause button
						btnPlay.setBackgroundResource(R.drawable.down_button_running);
					}
				}
			}
		});

		/**
		 * Button Click event for Repeat button Enables repeat flag to true
		 * */
//		btnRepeat.setOnClickListener(new View.OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				if (isRepeat) {
//					isRepeat = false;
//					Toast.makeText(getApplicationContext(), "Repeat is OFF",
//							Toast.LENGTH_SHORT).show();
//					btnRepeat.setImageResource(R.drawable.btn_repeat);
//				} else {
//					// make repeat to true
//					isRepeat = true;
//					Toast.makeText(getApplicationContext(), "Repeat is ON",
//							Toast.LENGTH_SHORT).show();
//					// make shuffle to false
//					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
//				}
//			}
//		});

	}

	public void playSong(String mp3Link) {
		// Play song
		try {
			mp.reset();
		    //mp.setDataSource("http://realaudio.rferl.org/voa/LERE/2014/05/23/6aec4121-dfa2-4bf5-9684-a4b9645bb6ff.mp3");
			if(mp3Link!=null){
				mp.setDataSource(mp3Link);
			}
			
			mp.prepare();
			mp.start();

			// Changing Button Image to pause image
			btnPlay.setBackgroundResource(R.drawable.down_button_running);

			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
		mHandler.postDelayed(mUpdateTimeTask, 100);
	}

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {		
			long totalDuration = mp.getDuration();
			long currentDuration = mp.getCurrentPosition();

			// Displaying Total Duration time
			songTotalDurationLabel.setText(""
					+ utils.milliSecondsToTimer(totalDuration));
			// Displaying time completed playing
			songCurrentDurationLabel.setText(""
					+ utils.milliSecondsToTimer(currentDuration));

			// Updating progress bar
			int progress = (int) (utils.getProgressPercentage(currentDuration,
					totalDuration));
			// Log.d("Progress", ""+progress);
			songProgressBar.setProgress(progress);

			// Running this thread after 100 milliseconds
			mHandler.postDelayed(this, 100);
		}
	};

	/**
	 * Parse html to get mp3Link
	 * 
	 * @param link
	 *            feed
	 */
	public String getMp3Link(String link) {
		String url = null;
		try {
			Elements elmUrl = new ParseHtmlAsyncTask(RssDetailsActitvity.this, this)
					.execute(link, Utility.newtag).get();
			
//			elmUrl = task.execute(link, Utility.newtag).get();
			if (elmUrl != null) {
				url = elmUrl.attr("src");
			} else {
				Toast.makeText(
						getApplicationContext(),
						"Can not connect to server to get element to parse mp3 Link",
						Toast.LENGTH_SHORT).show();
			}
			
//			final Elements elmUrl = new ParseHtmlAsyncTask(RssDetailsActitvity.this, new com.rssfeed.parser.GetLinkMp3Callback() {
//				
//				@Override
//				public void onSuccess() {
//					if (elmUrl != null) {
//						url = elmUrl.attr("src");
//					} 
//				}
//				
//				@Override
//				public void onFailture() {
//					Toast.makeText(RssDetailsActitvity.this, "Can not connect to server to get element to parse mp3 Link", 
//							Toast.LENGTH_LONG).show();
//							
//				}
//			}).execute(link, Utility.newtag).get();


		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return url;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(),
				totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		// check for repeat is ON or OFF
		if (isRepeat) {
			// repeat is on play same song again
			//mp3Link = "\"" + mp3Link + "\"";
			Log.d("Test1", "=" + mp3Link);
			playSong(mp3Link);		
		} else {
			// no repeat or shuffle ON - play next song
			//mp3Link = "\"" + mp3Link + "\"";
			Log.d("Test2", "=" + mp3Link);
			playSong(mp3Link);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		mHandler.removeCallbacks(mUpdateTimeTask);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mp.release();
	}

	@Override
	public void onSuccess() {
		if (mp3Link != null) {
			dbc = new DBController(this);
			dbc.updateMp3Link(rssFeed.getFeedId(), mp3Link);
		} 
		
		updateProgressBar();
	}

	@Override
	public void onFailture() {
		Toast.makeText(getApplicationContext(),
				"Can not get Mp3 Link from server", Toast.LENGTH_SHORT)
				.show();
		
		songCurrentDurationLabel.setVisibility(View.INVISIBLE);
		songTotalDurationLabel.setVisibility(View.INVISIBLE);
		
		mHandler.removeCallbacks(mUpdateTimeTask);
	}
}
